import Message from '@/components/message'
import axios, { AxiosError } from 'axios'
import { getProfile } from './storage'

// 备用地址：http://pcapi-xiaotuxian-front-devtest.itheima.net/
export const baseURL = 'http://pcapi-xiaotuxian-front.itheima.net/'
const request = axios.create({
  baseURL,
  // baseURL: 'https://apipc-xiaotuxian-front.itheima.net',
  timeout: 5000,
})
request.interceptors.request.use(
  function (config) {
    // 获取 token：从 store 获取或本地都可以
    const token = getProfile().token
    if (token) {
      // !号表示非空断言，断言前面一定有（不为 undefined 或 null）
      config.headers!.Authorization = `Bearer ${token}`
      // console.log(config.headers?.Authorization)
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
request.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function (error: AxiosError<{ code: string; message: string }>) {
    // AxiosError 泛型的第一个参数就是用来控制 error.response.data 的类型的
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    // console.log(error.response, 233)
    if (!error.response?.data) {
      Message.error('网络错误~~')
    } else {
      // Message.error((error.response.data as any).message)
      // error.response.data 的类型可以通过 AxiosError 的泛型参数控制
      Message.error(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

export default request
